const baseUrl = "http://localhost:8084";

const httpPost = (url, data, headers) => request(url, 'POST', data, headers);

const httpGet = (url, data, headers) => request(url, 'GET', data, headers);

/**
 * 发起http网络请求
 * @param {*} url 请求地址
 * @param {*} method 请求方法
 * @param {*} data 请求参数
 * @param {*} headers 请求头
 */
const request = (url, method, data, headers) => {
    if (!url.startsWith('/')) {
        url = `/${url}`;
    }
    /**
     * 返回一个异步方法
     * resolve：成功时会通过.then接收或者async -await得到
     * reject：异常时，.catch接收
     */
    return new Promise((resolve, reject) => {
        wx.request({
            url: baseUrl + url,
            method,
            header: {
                [wx.getStorageSync('tokenName') || 'Authorization']: wx.getStorageSync('token') || '',
                ...headers
            },
            data,
            success: ({
                data
            }) => {
                if (data.code == 200) {
                    resolve(data);
                } else {
                    wx.showToast({
                        title: data.message,
                        icon: 'error'
                    });
                    reject(data.message);
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: err.errMsg,
                    icon: 'error'
                });
                reject(err);
            }
        });
    });
}

/**
 * 文件上传
 * @param {*} filePath 
 */
const upload = (filePath) => {
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            filePath,
            name: 'file',
            url: baseUrl + '/common/upload',
            success: ({ data }) => {
                if (data.code == 200) {
                    resolve(data);
                } else {
                    wx.showToast({
                        title: data.message,
                        icon: 'error'
                    });
                    reject(data.message);
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: err.errMsg,
                    icon: 'error'
                });
                reject(err);
            }
        })
    });
}

/**
 * 获取图片预览地址
 * @param {*} filename 
 */
const fileView = (filename) => {
    if (filename) {
        if (filename.startsWith('http')) {
            return filename;
        }
        return `${baseUrl}/common/view/${filename}`;
    }
    return '';
}

export {
    httpGet,
    httpPost,
    upload,
    fileView
}